package com.scalar.chiptrack.utils;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.avalon.framework.ExceptionUtil;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;

/**
 * Created by Hareesh
 * Date: Dec 23, 2003
 * Time: 3:45:33 PM
 */

public class PDFGenerator
{
    public static boolean convertXML2PDF( String xmlPath, String xsltPath, String pdfPath ) throws IOException, FOPException, TransformerException
    {
        boolean success = false;
        //Construct driver
        Driver driver = new Driver();

        //Setup logger
        Logger logger = new ConsoleLogger( ConsoleLogger.LEVEL_ERROR );
        driver.setLogger( logger );
        MessageHandler.setScreenLogger( logger );

        //Setup Renderer (output format)
        driver.setRenderer( Driver.RENDER_PDF );

        if( ( xmlPath == null ) || ( xmlPath.trim().length() == 0 ) ) return false;
        if( ( xsltPath == null ) || ( xsltPath.trim().length() == 0 ) ) return false;
        if( ( pdfPath == null ) || ( pdfPath.trim().length() == 0 ) ) return false;

        File xmlFile = new File( xmlPath );
        File xsltFile = new File( xsltPath );
        File pdfFile = new File( pdfPath );

        //Setup output
        OutputStream out = null;
        try
        {
            out = new java.io.FileOutputStream( pdfFile );

            driver.setOutputStream( out );
            //Setup XSLT
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer( new StreamSource( xsltFile ) );

            //Setup input for XSLT transformation
            Source src = new StreamSource( xmlFile );

            //Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult( driver.getContentHandler() );

            //Start XSLT transformation and FOP processing
            transformer.transform( src, res );

            success = true;
        }
        finally
        {
            if( out != null )
			{
				try
				{
					out.close();
					out = null;
				}
				catch( IOException ignore ){}
			}
        }
        return success;
    }


    /*public static void main(String[] args) {
    try {
        //Setup directories
         File baseDir = new File(".");
         File outDir = new File(baseDir, ".");
         outDir.mkdirs();

         //Setup input and output files
         String xmlFile = "d:/chiptrack/chiptrac_mail_temp_dir/CommercialInvoice.xml";
         String xsltFile = "d:/chiptrack/config/commercialInvoice.xsl";
         String pdfFile = "d:/chiptrack/chiptrac_mail_temp_dir/CommercialInvoice.pdf";

         //System.out.println("Input: XML (" + xmlFile + ")");
         //System.out.println("Stylesheet: " + xsltFile);
         //System.out.println("Output: PDF (" + pdfFile + ")");
         System.out.println();

         System.out.println("Transforming...");
         PDFGenerator.convertXML2PDF(xmlFile, xsltFile, pdfFile);

          System.out.println("Success!");
        } catch (Exception e) {
            System.err.println(ExceptionUtil.printStackTrace(e));
            System.exit(-1);
        }
    }*/
}
